﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jim.K3Cloud;

/// <summary>
///  金蝶云星空多语言转换
/// </summary>
public class LocaleValueConverter : JsonConverter
{
    //public override bool CanWrit=> true;

    public override bool CanRead => true;

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        string value = string.Empty;
        try
        {
            serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
            serializer.NullValueHandling = NullValueHandling.Ignore;

            //Debug.WriteLine($"LocaleValueConverter-ReadJson类型： {reader.TokenType}");
            // 使用 JToken.Load 方法将 JsonReade中的数据加载到 JToken 对象中
            JToken token = JToken.Load(reader);
            if (token != null)
            {
                LocaleValue localValue = token.ToObject<LocaleValue>();
                value = localValue.ToString();
                //Debug.WriteLine($"json：{token.ToString()} 转为{value}");
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine($"json转换错误:{e.Message}");
        }
        return value;
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }
}